package com.chen.wxchat.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chen.wxchat.entity.AnswerList;
import com.chen.wxchat.entity.FriendCircle;
import com.chen.wxchat.entity.UserInfo;
import com.chen.wxchat.service.AnswerService;
import com.chen.wxchat.service.FriendCircleService;
import com.chen.wxchat.service.UserInfoService;
import com.chen.wxchat.tools.DateTool;
import com.chen.wxchat.tools.HttpUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

@RestController
@RequestMapping("/superadmin")
public class AnswerController {
    @Autowired
    private AnswerService answerService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private FriendCircleService circleService;

    private static Logger log = LoggerFactory.getLogger(AnswerController.class);

    @RequestMapping(value = "/findAnswer",method = RequestMethod.GET)
    public Map<String,Object> listAnswer(String answerContent){
        Map<String,Object> modelMap = new HashMap<String, Object>();
        List<AnswerList> answerList = answerService.getAnswerList(answerContent);
        log.info("测试日志输出情况");
        modelMap.put("list",answerList);
        log.info(modelMap.toString());
        return modelMap;
    }
    @RequestMapping(value = "/findAnswerByType",method = RequestMethod.GET)
    public Map<String,Object> findAnswerByType(String typeId){
        Map<String,Object> modelMap = new HashMap<String, Object>();
        List<AnswerList> answerList = null;
        if (typeId.equals("1")){
            answerList = answerService.getAnswerList(null);
        }else {
            answerList = answerService.getAnswerListBytypeId(typeId);
        }
        modelMap.put("list",answerList);
        return modelMap;
    }
    @RequestMapping(value = "/addAnswer",method = RequestMethod.POST)
    public Map<String,Object> addAnswer(@RequestBody AnswerList answerList) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        if (answerList == null) {
            modelMap.put("success", false);
            modelMap.put("errMsg", "后台程序报错");
        } else {
            answerList.setAttention("1");
            modelMap.put("success", answerService.addAnswer(answerList));
        }
        return modelMap;
    }
    @RequestMapping(value = "/getOpenId",method = RequestMethod.GET)
    public Map<String,Object> getOpenId(String code){
        Map<String,Object> modelMap = new HashMap<String, Object>();
        String WX_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET" +
                "&js_code=JSCODE&grant_type=authorization_code";
        String requestUrl = WX_URL.replace("APPID", "******").//填写自己的appid
                replace("SECRET", "*******").replace("JSCODE", code).//填写自己的appsecret，
                replace("authorization_code", "authorization_code");
        String reslut = HttpUtil.get(requestUrl);
        log.info(reslut);
        //解析相应内容（转换成json对象）
        JSONObject convertvalue = new JSONObject();
        convertvalue = (JSONObject) JSON.parse(reslut);
        //用户的唯一标识（openid）
        String Openid =String.valueOf(convertvalue.get("openid"));
        modelMap.put("openid",Openid);
        return modelMap;
    }
    @RequestMapping(value = "/registerUserFirst",method = RequestMethod.POST)
    public Map<String,Object> registerUserFirst(@RequestBody UserInfo userInfo) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        UserInfo userRes = userInfoService.getUserInfoById(userInfo.getUserId());
        if (userInfo == null || userRes != null) {
            modelMap.put("success", false);
            modelMap.put("errMsg","该用户已存在");
            modelMap.put("user",userRes);
        } else {
            modelMap.put("success", userInfoService.addUser(userInfo));
        }
        return modelMap;
    }
    @RequestMapping(value = "/registerUserSecond",method = RequestMethod.POST)
    public Map<String,Object> registerUserSecond(@RequestBody UserInfo userInfo) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        log.info(userInfo.toString());
        if (userInfo == null || userInfoService.getUserStateInfoById(userInfo.getUserId()) != null) {
            modelMap.put("success", false);
            modelMap.put("errMsg","该用户已在申请队列，请勿多次申请");
        } else {
            modelMap.put("success", userInfoService.registerUser(userInfo));
        }
        return modelMap;
    }
    @RequestMapping(value = "/registerUserThree",method = RequestMethod.POST)
    public Map<String,Object> registerUserThree(@RequestBody UserInfo userInfo) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        log.info(userInfo.toString());
        if (userInfo == null) {
            modelMap.put("success", false);
            modelMap.put("errMsg","后台程序报错，请稍后重试");
        } else {
            userInfo.setUserState("2");
            modelMap.put("success", userInfoService.registerUser(userInfo));
        }
        return modelMap;
    }

    @RequestMapping(value = "/getRegisterUser",method = RequestMethod.GET)
    public Map<String,Object> getRegisterUser(){
        Map<String,Object> modelMap = new HashMap<String, Object>();
        List<UserInfo> registerUserList = userInfoService.getRegisterUserList();
        log.info("测试日志输出情况");
        log.info(""+registerUserList.size());
        if (registerUserList!=null){
            modelMap.put("success",true);
            modelMap.put("list",registerUserList);
        }else {
            modelMap.put("success",false);
            modelMap.put("errMsg","后台程序报错，请稍后重试");
        }
        log.info(modelMap.toString());
        return modelMap;
    }

    @RequestMapping(value = "/getFriendCircleList",method = RequestMethod.GET)
    public Map<String,Object> getList(String userId){
        Map<String,Object> modelMap = new HashMap<String, Object>();
        List<FriendCircle> list = circleService.getFriendCircleList(userId);
        modelMap.put("success",true);
        modelMap.put("list",list);
        return modelMap;
    }
    @RequestMapping(value = "/uploadData",method = RequestMethod.POST)
    public Map<String,Object> uploadData(@RequestBody FriendCircle circle){
        Map<String,Object> modelMap = new HashMap<String, Object>();
        String ipaddress="http://localhost:8080/wxchat/";
        String[] array;
        String imagePath = "";
        if (circle == null){
            modelMap.put("success",false);
            modelMap.put("errMsg","后台程序报错，请稍后重试");

        }else {
            array = circle.getImageList().split(",");
//            String[] arraytarget = new String[array.length];
            for(int i = 0;i<array.length;i++){
                imagePath = ipaddress+ array[i] +","+ imagePath ;
            }
            circle.setImageList(imagePath.substring(0,imagePath.length()-1));
            modelMap.put("success",circleService.addFriendCircle(circle));
        }

        return modelMap;
    }

    /**
     * 图片上传
     *
     * @return
     * @throws Exception
     */
    //@ExcLoginInterceptor 自定义的拦截器注解
    @RequestMapping(value = "/upload")
    public Map<String,Object>  uploadPicture(@RequestParam(value = "file") MultipartFile files[],HttpServletRequest request) throws Exception{
        //获取文件需要上传到的路径
        Map<String,Object> modelMap = new HashMap<String, Object>();
        if (files.length==0) {
            modelMap.put("success",false);
            return modelMap;
        }
        for (int i = 0; i < files.length; i++) {
            MultipartFile file =files[i];
            String fileName = file.getOriginalFilename();
            if (("").equals(fileName)) {
                break;
            }
            String pre = String.valueOf(System.currentTimeMillis());
            String fileType = fileName.substring(fileName.lastIndexOf("."),fileName.length());
            //file-directory
//            String path = request.getServletContext().getRealPath("/upload")+"/";
            String upload = "/Users/citicbank_chen/IdeaProjects/wxchat/upload/";

            File folder = new File(upload);
            if (!folder.exists() && !folder.isDirectory()) {
                folder.mkdir();
            }

            fileName = pre+fileType;
            //存储图片信息
            File targetFile = new File(upload+fileName);
            try {
                file.transferTo(targetFile);

            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
            modelMap.put("success",true);
            modelMap.put("imagename",fileName);
        }
        return modelMap;
    }



}
